<template>
    <div class="pageBox" id="bookArea"
         v-loading="showLoading"
         element-loading-text="仿真书加载中..."
         element-loading-spinner="el-icon-loading"
         element-loading-background="#fff" >
        <div class="flipbook" id="flipbook">
            <div v-for="(item, index) in objContents" style="width: 100%; height: 100%; overflow: hidden;">
                <div class="pagelayer">
                    <div class="sjRsub">
                        <span>
                            <!--讲义-->
                        </span>
                    </div>
                    <div class="page-child"
                         v-bind:style="{'margin-left':  getOffset(index)}" v-html="item">
                    </div>
                </div>
            </div>
        </div>
        <div class="bookEdit">
            <span class="bRfsh" title="刷新" @click="refreshBook"></span>
            <span class="bPrev" title="上一页" @click="turnPage('prev')"></span>
            <span class="bPnext" title="下一页" @click="turnPage('next')"></span>
            <div class="bPall">共
                <div>{{totalPages}}</div>
                页
            </div>
        </div>
        <div id="tempFather" class="temp-father">
            <div id="template">
            </div>
        </div>
    </div>
</template>
<script>
    import {Observer} from '../../core/util'
    import "../../../../static/eBook/js/turn.min";

    let objBook; // 仿真书对象
    export default {
        components: {},
        data() {
            return {
                curPage: 1, // 当前页码
                totalPages: 0, // 一共多少页
                objContents: {}, // 内容对象
                showLoading: false,
            }
        },
        computed: {
            // ...mapState(['rightBarVisible']),
        },
        watch: {},
        methods: {
            /**
             * 销毁book的dom树
             */
            destroyBook() {
                if (objBook && typeof objBook.turn === "function" && objBook.turn("is")) { // 已有仿真书实例
                    objBook.turn("destroy");
                    objBook.html("");
                    objBook.attr("style", "");
                    objBook.attr("class", "flipbook");
                    objBook = null;
                }
            },
            /**
             * 计算分页数
             */
            countPages() {
                let domEditor = document.getElementById(window.editorId);
                if (!domEditor) return; // editor的dom还未加载
                this.getShowContent().then(content => {
                    // console.log(content);
                    // content = content.replace(/_ueditor_page_break_tag_/g, "<hr/>");
                    let arrContent = content.split('_ueditor_page_break_tag_'); // 按分页符切分内容
                    const tempFather = document.getElementById("tempFather");
                    const $tempChild = $("#template");
                    let arrPageAndContent = [];
                    for (let i = 0; i < arrContent.length; i++) {
                        const partContent = arrContent[i];
                        if(partContent){
                            $tempChild.html(partContent); // 虚拟容器放置内容
                            let pages = Math.ceil((parseInt(tempFather.scrollWidth) + 100) / 550); // 计算页数
                            $tempChild.html(""); // 虚拟容器清空内容
                            arrPageAndContent.push({
                                page: pages,
                                content: partContent
                            });
                        }
                    }
                    // console.log(arrPageAndContent);
                    this.beforeRenderBook(arrPageAndContent);
                });
            },
            /**
             * 得到仿真书需要展示的内容
             */
            getShowContent(){
                return new Promise((resolve, reject) => {
                    let domQuote = document.getElementById("quoteList");
                    if(domQuote && domQuote.style.display !== "none"){
                        let url = "/api/Editor/GetBookV2"
                            , bookId = window.resourceID;
                        if(!window.typeId){
                            url = "/api/Editor/GetBook";
                            bookId = window.moduleCode;
                        }
                        // 当前文档有引用，需要从数据库拿值
                        axios.get(url, {
                            params: {
                                bookId: bookId
                            }
                        }).then(res => {
                            if (res && res.data && res.data.Code === 200) {
                                let originalData = "";
                                if (typeof res.data.Data === "object" && res.data.Data) {
                                    originalData = res.data.Data.Content || "";
                                } else {
                                    originalData = res.data.Data || "";
                                }
                                resolve(originalData);
                            } else {
                                reject();
                            }
                        }).catch(err => {
                            reject(err);
                        });
                    } else {
                        // 没有引用，直接得到编辑器里的内容
                        let content = UE.getEditor(window.editorId).getContent();
                        resolve(content);
                    }
                })
            },
            /**
             * 在渲染仿真书之前执行的操作
             * @param arrPageAndContent 页码和内容对象构成的数组
             */
            beforeRenderBook(arrPageAndContent) {
                if (objBook && typeof objBook.turn === "function" && objBook.turn("is")) { // 已有仿真书实例
                    this.destroyBook();
                    this.renderBook(arrPageAndContent);
                }else{ // 第一次加载仿真书
                    this.renderBook(arrPageAndContent);
                }
            },
            /**
             * 渲染仿真书
             * @param arrPageAndContent 页码和内容对象构成的数组
             */
            renderBook(arrPageAndContent){
                // 赋值页数和内容数组
                let pages = 0;
                let objContent = {};
                for (let i = 0; i < arrPageAndContent.length; i++) {
                    const obj = arrPageAndContent[i];
                    pages += obj.page;
                    for (let j = 0; j < obj.page; j++) {
                        objContent[i + "_" + j] = obj.content; // 取_后面的第二个数字作为当前偏移量的索引
                    }
                }
                if(pages === 0 ){
                    this.totalPages = 1;
                    this.objContents = {
                        "0_0": ""
                    }
                } else {
                    this.totalPages = pages;
                    this.objContents = objContent;
                }
                // renderbook
                this.asyncFun("vue").then(this.initBook);// 仿真书dom加载出来之后，执行初始化的方法
            },
            /**
             * 计算偏移量
             * @param i 当前偏移量的索引
             */
            getOffset(i){
                i = i.replace(/\d+_/g, "");
                return i * (-550) + 'px';
            },
            /**
             * 初始化仿真书实例对象--此处后期应考虑和仿真书一致【样式表，特殊标签，行内样式，区域和渲染方式】
             */
            initBook() {
                let vm = this;
                objBook = $("#flipbook");
                objBook.turn({
                    display: 'single',
                    acceleration: true,
                    gradients: true,
                    autoCenter: true,
                    elevation: 50,
                    when: {
                        turning: function(event, page, pageObject) {
                            vm.pauseVideoAudio();
                        }
                    }
                });
                // 只有1页报错的问题
                objBook.bind("start", function(event, pageObject, corner) {
                    if(objBook.turn("hasPage", pageObject.next) === false){ // 下一页没有了
                        event.preventDefault();
                    }
                });
                this.showLoading = false;
            },
            /**
             * 仿真书跳转
             * @param dir 方向
             */
            turnPage(dir) {
                if (!objBook) return;
                if (dir === "prev") { // 上一页
                    objBook.turn('previous');
                } else if (dir === "next") { // 下一页
                    objBook.turn('next');
                }
            },
            /**
             * 异步操作
             */
            asyncFun(type, time){
                return new Promise( (resolve, reject) => {
                    if(type === "vue"){
                        this.$nextTick(resolve);
                    }else{
                        setTimeout(resolve, time);
                    }
                });
            },
            /**
             * 刷新仿真书的方法
             */
            refreshBook(){
                Observer.fire("refreshBook");
            },
            /**
             * 播放时暂停视频和音频
             */
            pauseVideoAudio(){
                let arrVideo = Array.prototype.slice.call(document.getElementsByTagName("video"));
                let arrAudio = Array.prototype.slice.call(document.getElementsByTagName("audio"));
                let arrMedia =[...arrAudio, ...arrVideo];
                arrMedia.forEach((item) => {
                    item.pause();
                });
            }
        },
        created: function () {
            Observer.register("refreshBook", (data) => {
                // 右侧仿真书区域显示之后，执行计算页数的方法，右侧区域隐藏时，计算页数会出错（显示为1）
                this.showLoading = true;
                this.objContents = {}; // 清空vueDom
                this.asyncFun("original", 500).then(this.countPages);
            });
            // 20180506 lyu 去掉这个事件
            // Observer.register("removeBook", (data) => {
            //     // 删除仿真书内容
            //     this.objContents = {}; // 清空vueDom
            // });
        },
        mounted: function () {
        }
    }
</script>

<style scoped>
    @import "./../../../assets/css/bookpreview.css";
    @import "./../../../assets/css/editorstyle.css";
    @import "./../../../assets/css/bookbasic.css";

    .flipbook .page {
        margin: 0;
    }
</style>
